#!/bin/bash

set -e

DIR=$(readlink -f $(dirname $0))
source $DIR/common.sh


if [ $# -eq 0 ]
then
	echo "Usage:  $DIR/$0 sd|ram"
	exit 1
fi
while [[ $# -gt 0 ]]
do
	key="$1"
	case $key in
		sd | ram )
			FILE_TYPE=$key
			;;
		*)
			echo "Unknown arguments:  $1"
			exit 1
			;;
	esac
	shift
done

pushd $DIR/$BUSYBOX_PATH

[ -d _install ] || { echo "Build busybox ..." && make distclean && make defconfig &&  make -j4 && make install ; }

sudo rm -rf rootfs tmpfs
mkdir rootfs
mkdir -p rootfs/{lib,etc/init.d,dev,proc,usr,var,tmp,home,root,mnt,bin,sbin,sys,dev/shm}
cp ./_install/* -r rootfs

cp -r $(dirname $(locate arm-linux-gnueabi-gcc|head -1))/../arm-linux-gnueabi/libc/lib/* rootfs/lib
#cp -r /usr/local/gcc-linaro-7.2.1-2017.11-x86_64_arm-linux-gnueabi/arm-linux-gnueabi/libc/lib/* rootfs/lib
sudo mknod rootfs/dev/tty1 c 4 1
sudo mknod rootfs/dev/tty2 c 4 2
sudo mknod rootfs/dev/tty3 c 4 3
sudo mknod rootfs/dev/tty4 c 4 4

cat > rootfs/etc/init.d/rcS <<EOF
#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
/sbin/mdev -s
EOF

chmod +x rootfs/etc/init.d/rcS
echo "All files for rootfs are ready. Make image"

if [ $FILE_TYPE == "sd" ]
then
	[ -f $ROOTFS_FILE ] && rm -rf $ROOTFS_FILE
	dd if=/dev/zero of=$ROOTFS_FILE bs=1M count=256
	mkfs.ext3 -F $ROOTFS_FILE

    sudo rm -rf tmpfs
	mkdir tmpfs
	sudo mount -t ext3 $ROOTFS_FILE tmpfs -o loop
	sudo cp -r rootfs/* tmpfs/
	sudo umount tmpfs

else
	pushd rootfs
	find . | cpio -o --format=newc > ../rootfs.img.cpio
	popd
	gzip -c rootfs.img.cpio > $ROOTFS_FILE

fi

sudo rm -rf rootfs tmpfs

popd

exit 0
